package com.my.ph.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.my.ph.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service("seedvault")
@Slf4j
public class SeedvaultUploadServiceImpl implements UploadService {

    @Override
    public String upload(String filePath) {
        HttpResponse response = HttpRequest.post("https://img.seedvault.cn/api/v1/upload")
                .form("file", FileUtil.file(filePath))
                .header("Authorization", "Bearer Bearer 12|BT8nSLE1qu8Q70YzEwZqQUg5WTws3W9WMH8tCeK8")
                .header("Content-Type", "multipart/form-data")
                .header("Accept", "application/json")
                .execute();
        if (response.getStatus() == 401) throw new RuntimeException("未登录或授权失败");
        if (response.getStatus() == 403) throw new RuntimeException("管理员关闭了接口功能");
        if (response.getStatus() == 429) throw new RuntimeException("超出请求配额，请求受限");
        if (response.getStatus() == 500) throw new RuntimeException("服务端出现异常");
        JSONObject bodyObj = JSONObject.parseObject(response.body());
        log.info("上传路径：{}，上传返回：{}", filePath, bodyObj);
        if (!bodyObj.getBoolean("status")) throw new RuntimeException(bodyObj.getString("message"));
        JSONObject data = bodyObj.getJSONObject("data");
        return data.getJSONObject("links").getString("url");
    }

}
